<template>
  <div class="app-container">
    <div class="question-aside">
      <div class="aside-title">试题分类</div>
      <el-divider />
      <el-button type="text" @click="appendNode('add', 1, treeData)">
        添加一级分类
      </el-button>
      <el-tree
        ref="classifyTree"
        node-key="kindId"
        highlight-current
        default-expand-all
        :props="treeProps"
        :data="treeData"
        @node-click="handleNodeClick"
      >
        <span slot-scope="{ node, data }" class="custom-tree-node">
          <span>{{ node.label }}</span>
          <span v-if="data.parentId !== 0">
            <el-link
              :underline="false"
              icon="el-icon-edit-outline"
              @click.stop="appendNode('edit', 2, data)"
            />
            <el-link
              :underline="false"
              icon="el-icon-delete"
              @click.stop="removeNode(node, data)"
            />
          </span>
          <span v-else>
            <el-link
              :underline="false"
              icon="el-icon-circle-plus-outline"
              @click.stop="appendNode('add', 2, data)"
            />
            <el-link
              :underline="false"
              icon="el-icon-edit-outline"
              @click.stop="appendNode('edit', 1, data)"
            />
            <el-link
              :underline="false"
              icon="el-icon-delete"
              @click.stop="removeNode(node, data)"
            />
          </span>
        </span>
      </el-tree>
    </div>

    <div class="question-main">
      <el-row type="flex" justify="space-between">
        <span>
          <el-button
            type="primary"
            plain
            :disabled="!selectedTree.id"
            @click="add"
          >
            添加试题
          </el-button>
          <el-button
            type="danger"
            plain
            :disabled="questionIds.length === 0"
            @click="batchRemove"
          >
            批量删除
          </el-button>
        </span>
        <el-form inline :model="formInline">
          <el-form-item label="试题内容">
            <el-input
              v-model="formInline.titleContent"
              clearable
              placeholder="请输入试题内容"
            />
          </el-form-item>
          <el-form-item label="题型">
            <el-select
              v-model="formInline.questionType"
              clearable
              placeholder="选择题型"
            >
              <el-option label="全部" value="" />
              <el-option
                v-for="(item, index) in questionTypeList"
                :key="index"
                :label="item"
                :value="index + 1"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="search">查询</el-button>
          </el-form-item>
        </el-form>
      </el-row>

      <el-table
        v-loading="listLoading"
        :data="tableData"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          align="center"
          :selectable="renderCheckbox"
          width="55"
        />
        <el-table-column
          label="试题内容"
          prop="titleContent"
          show-overflow-tooltip
        />
        <el-table-column
          label="题型"
          align="center"
          prop="questionTypeName"
          width="80"
        />
        <el-table-column label="分类" align="center">
          <template slot-scope="{ row }">
            <span>
              {{ row.questionKindParentName + "/" + row.questionKindName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="80">
          <template slot-scope="{ row }">
            <span v-if="row.status == 3">已作废</span>
            <el-tooltip
              v-else
              :content="row.status == 2 ? '已发布' : '未发布'"
              placement="top"
            >
              <el-switch
                :disabled="row.status == 2"
                :value="row.status === 2"
                @change="publish(row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          label="创建人"
          align="center"
          prop="createBy"
          width="120"
        />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="170"
        />
        <el-table-column label="操作" align="center" width="160">
          <template slot-scope="{ row }">
            <el-button size="mini" type="primary" plain @click="edit(row)">
              {{ row.status == 1 ? "编辑" : "查看" }}
            </el-button>
            <el-button
              v-if="row.status == 1"
              size="mini"
              type="danger"
              plain
              @click="remove(row)"
            >
              删除
            </el-button>
            <el-button
              v-else-if="row.status == 2"
              size="mini"
              type="warning"
              plain
              @click="abandon(row)"
            >
              作废
            </el-button>
            <el-button
              v-else
              size="mini"
              type="success"
              plain
              @click="resume(row)"
            >
              恢复
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="padding: 10px" />
      <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="pageNum"
        :page-size="pageSize"
        :total="total"
        @size-change="onPageSizeChange"
        @current-change="onCurrentPageChange"
      />
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import {
  treeSelect,
  addClassify,
  editClassify,
  deleteClassify,
  getQuestionPage,
  deleteQuestion,
  abandonQuestion,
  restorePublishQuestion,
  publishQuestion,
} from "@/api2/question";

export default {
  name: "questionList",
  data() {
    return {
      treeData: [],
      treeProps: {
        children: "children",
        label: "name",
      },
      selectedTree: {},
      formInline: {},
      questionTypeList: ["单选题", "多选题", "判断题", "填空题", "简答题"],
      questionIds: [],
      tableData: [],
      listLoading: false,
      pageNum: 1,
      pageSize: 10,
      total: 0,
    };
  },
  mounted() {
    this.getTreeData();
  },
  computed: {
    ...mapState("project", ["isInclude"]),
  },
  activated() {
    !this.isInclude && this.getTreeData();
    this.IS_INCLUDE(true);
  },
  methods: {
    ...mapMutations("project", ["IS_INCLUDE"]),
    renderCheckbox(row) {
      return row.status == 2 ? 0 : 1;
    },
    // 3修改分类名称  2新增二级分类  1新增一级分类
    appendNode(type, level, data) {
      const tips = type === "edit" ? "修改" : "添加";
      const rankTxt = level === 1 ? "一级" : "二级";

      this.$prompt(`请输入${rankTxt}分类名称`, tips, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        closeOnClickModal: false,
        inputValue: type === "edit" ? data.name : undefined,
        inputValidator: (value) => {
          if (!value) {
            return "名称不能为空！";
          }
          if (value.length > 10) {
            return "名称限制10个字以内！";
          }
        },
      })
        .then(async ({ value: name }) => {
          if (type === "edit") {
            await editClassify({
              parentId: data.parentId,
              kindId: data.kindId,
              name,
            });
            this.$set(data, "name", name);
          } else {
            const { data: kindId } = await addClassify({
              parentId: level === 1 ? 0 : data.kindId,
              name,
            });
            if (level === 1) {
              const newChild = { kindId, name, parentId: 0, children: [] };
              data.push(newChild);
            } else {
              const newChild = { kindId, name, parentId: data.kindId };
              data.children.push(newChild);
            }
          }

          this.$message({
            type: "success",
            message: `分类名称${tips}成功`,
          });
        })
        .catch(() => {});
    },
    removeNode(node, data) {
      this.$confirm("此操作将删除该分类与旗下所有试题, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await deleteClassify(data.kindId);
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex((d) => d.kindId === data.kindId);
          children.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {});
    },
    handleNodeClick(data) {
      if (data.parentId !== 0) {
        this.$set(this.selectedTree, "id", data.kindId);
        this.$set(this.selectedTree, "name", data.name);
        this.getList();
      } else {
        this.$refs.classifyTree.setCurrentKey(this.selectedTree.id);
      }
    },
    async getTreeData() {
      const res = await treeSelect();
      this.treeData = res.data;

      this.$nextTick(() => {
        const data = res.data.find((item) => item.children?.length > 0);
        this.$set(this.selectedTree, "id", data?.children[0]?.kindId);
        this.$set(this.selectedTree, "name", data?.children[0]?.name);
        if (this.selectedTree.id && this.selectedTree.name) {
          this.$refs.classifyTree.setCurrentKey(this.selectedTree.id);
          this.getList();
        }
      });
    },
    getList() {
      this.listLoading = true;
      getQuestionPage({
        ...this.formInline,
        kindId: this.selectedTree.id,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }).then((data) => {
        this.listLoading = false;
        this.tableData = data.data;
        this.total = data.total;
      });
    },
    onPageSizeChange(val) {
      this.pageSize = val;
      this.pageNum = 1;
      this.getList();
    },
    onCurrentPageChange(val) {
      this.pageNum = val;
      this.getList();
    },
    search() {
      this.pageNum = 1;
      this.getList();
    },
    handleSelectionChange(val) {
      const ids = val.map((item) => item.id);
      this.questionIds = ids;
    },
    add() {
      this.$emit("change", {
        componentName: "addQuestion",
        classify: this.selectedTree,
      });
    },
    async batchRemove() {
      this.$confirm("确定删除已选中的数据吗?", {
        type: "warning",
      })
        .then(async () => {
          await deleteQuestion(this.questionIds.join());
          this.getList();
          this.$message.success("批量删除成功");
        })
        .catch(() => {});
    },
    edit(row) {
      const params = {
        componentName: "addQuestion",
        question: {
          id: row.id,
          type: row.questionType,
        },
        classify: this.selectedTree,
      };
      this.$emit("change", params);
    },
    async publish(row) {
      let { status, id } = row;
      status = status == 2 ? 1 : 2;
      await publishQuestion({ id, status });
      row.status = status;
      this.$message.success(status == 2 ? "发布成功" : "取消发布");
    },
    abandon({ id }) {
      this.$confirm("确定作废此项数据吗?", {
        type: "warning",
      })
        .then(async () => {
          const params = { id, status: 3 };
          await abandonQuestion(params);
          this.getList();
          this.$message.success("作废成功");
        })
        .catch(() => {});
    },
    resume({ id }) {
      this.$confirm("确定要恢复为已发布状态吗?", {
        type: "warning",
      })
        .then(async () => {
          const params = { id, status: 2 };
          await restorePublishQuestion(params);
          this.getList();
          this.$message.success("作废成功");
        })
        .catch(() => {});
    },
    remove(row) {
      this.$confirm("确定删除此项数据吗?", {
        type: "warning",
      })
        .then(async () => {
          await deleteQuestion(row.id);
          this.getList();
          this.$message.success("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  height: 100%;
  display: flex;
  background-color: #f4f5fc;
  > div {
    padding: 12px 20px;
    border: 1px solid #dcdfe6;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
    background-color: #fff;
  }
  .question-aside {
    width: 250px;
    margin-right: 10px;
    .aside-title {
      font-size: 18px;
      line-height: 30px;
      font-weight: bold;
    }
  }
  .question-main {
    flex: 1;
    overflow: auto;
  }
}
.el-divider--horizontal {
  margin: 12px 0 8px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 5px;
  .el-link + .el-link {
    margin-left: 8px;
  }
}
::v-deep {
  .el-tree-node__content {
    height: 30px;
  }
  .el-tree-node.is-current > .el-tree-node__content {
    color: #3b95ff;
  }
}
</style>
